#include "SceneManagerModel.h"
#include "NodeData.h"
#include <osg/Group>

SceneManagerModel::SceneManagerModel()
{
}

SceneManagerModel::~SceneManagerModel(void)
{
}


void SceneManagerModel::addObject(ObjectType type, osg::Node* pNode)
{
	if(type != Model)
	{
		SceneManager::addObject(type, pNode);
	}
	else
	{
		int rows = rowCount();
		beginInsertRows(QModelIndex(), rows, rows);
		SceneManager::addObject(type, pNode);
		endInsertRows();
	}
}


void SceneManagerModel::removeObject(ObjectType type, osg::Node* pNode)
{
	if(type != Model)
	{
		SceneManager::removeObject(type, pNode);
	}
	else
	{
		osg::Group* pGroup = getObjectGroup(type);
		unsigned int i = pGroup->getChildIndex(pNode);
		beginRemoveRows(QModelIndex(), i, i);
		SceneManager::removeObject(type, pNode);
		endRemoveRows();
	}
}


const osg::Node* SceneManagerModel::node(const QModelIndex& index) const
{
	return getObjectGroup(SceneManager::Model)->getChild( index.row() );
}


osg::Node* SceneManagerModel::node(const QModelIndex& index)
{
	return getObjectGroup(SceneManager::Model)->getChild( index.row() );
}


QModelIndex SceneManagerModel::index(const osg::Node* node) const
{
	int i = getObjectGroup(SceneManager::Model)->getChildIndex(node);
	if(i == getObjectGroup(SceneManager::Model)->getNumChildren())
	{
		return QModelIndex();
	}
	else
	{
		return createIndex( i, 0 );
	}
}


int SceneManagerModel::rowCount( const QModelIndex& ) const
{
	return getObjectGroup(SceneManager::Model)->getNumChildren();
}


QVariant SceneManagerModel::data ( const QModelIndex & index, int role /*= Qt::DisplayRole*/ ) const
{
	if( !index.isValid() )
	{
		return QVariant();
	}

	const osg::Node* pNode = node(index);
    if(role == Qt::DisplayRole)
	{
		return pNode->getName().c_str();
	}
    else if(role == Node)
	{
		return pNode;
	}
    else if(role == Selectable)
    {
        return dynamic_cast<const NodeData*>(pNode->getUserData())->selectable;
    }
	return QVariant();
}


QVariant SceneManagerModel::headerData ( int /*section*/, Qt::Orientation /*orientation*/, int /*role = Qt::DisplayRole*/ ) const
{
	return "NodeNames";
}


Qt::ItemFlags SceneManagerModel::flags(const QModelIndex &index) const
{
	if (!index.isValid())
	{
		return Qt::ItemIsEnabled;
	}

	return QAbstractListModel::flags(index) | Qt::ItemIsEditable;
}


bool SceneManagerModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
	if (index.isValid() && role == Qt::EditRole)
	{
		osg::Node* pNode = getObjectGroup(SceneManager::Model)->getChild( index.row() );
		pNode->setName( value.toString().toAscii().data() );
		emit(dataChanged(index, index));

		return true;
	}

	return false;
}
